//* https://www.cnblogs.com/zl03jsj/p/8047259.html

class Point {
    constructor(x, y, time) {
        this.x = x;
        this.y = y;
        this.time = time || Date.now();
    }

    distanceTo(start) {
        return Math.sqrt(Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2));
    }

    equals(other) {
        return this.x === other.x && this.y === other.y && this.time === other.time;
    }

    velocityFrom(start) {
        return this.time !== start.time ? this.distanceTo(start) / (this.time - start.time) : 0;
    }
}

class Bezier {
    constructor(startPoint, control2, control1, endPoint, startWidth, endWidth) {
        this.startPoint = startPoint;
        this.control2 = control2;
        this.control1 = control1;
        this.endPoint = endPoint;
        this.startWidth = startWidth;
        this.endWidth = endWidth;
    }

    static fromPoints(points, widths) {
        const c2 = this.calculateControlPoints(points[0], points[1], points[2]).c2;
        const c3 = this.calculateControlPoints(points[1], points[2], points[3]).c1;
        return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);
    }

    static calculateControlPoints(s1, s2, s3) {
        const dx1 = s1.x - s2.x;
        const dy1 = s1.y - s2.y;
        const dx2 = s2.x - s3.x;
        const dy2 = s2.y - s3.y;
        const m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };
        const m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };
        const l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
        const l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
        const dxm = m1.x - m2.x;
        const dym = m1.y - m2.y;
        const k = l2 / (l1 + l2);
        const cm = { x: m2.x + dxm * k, y: m2.y + dym * k };
        const tx = s2.x - cm.x;
        const ty = s2.y - cm.y;
        return {
            c1: new Point(m1.x + tx, m1.y + ty),
            c2: new Point(m2.x + tx, m2.y + ty),
        };
    }

    // Returns approximated length. Code taken from https://www.lemoda.net/maths/bezier-length/index.html.
    length() {
        const steps = 10;
        let length = 0;
        let px;
        let py;
        for (let i = 0; i <= steps; i += 1) {
            const t = i / steps;
            const cx = this.point(t, this.startPoint.x, this.control1.x, this.control2.x, this.endPoint.x);
            const cy = this.point(t, this.startPoint.y, this.control1.y, this.control2.y, this.endPoint.y);
            if (i > 0) {
                const xdiff = cx - px;
                const ydiff = cy - py;
                length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);
            }
            px = cx;
            py = cy;
        }
        return length;
    }

    // Calculate parametric value of x or y given t and the four point coordinates of a cubic bezier curve.
    point(t, start, c1, c2, end) {
        // prettier-ignore
        return (start * (1.0 - t) * (1.0 - t) * (1.0 - t))
            + (3.0 * c1 * (1.0 - t) * (1.0 - t) * t)
            + (3.0 * c2 * (1.0 - t) * t * t)
            + (end * t * t * t);
    }
}

class WritePad {
    constructor(canvas, options) {
        this.canvas = canvas;
        this._ctx = canvas.getContext('2d');
        this.minDistance = 5;
        this.penColor = 'black';
        this.backgroundColor = '#fff';
        this.backgroundIsEmpty = options?.backgroundIsEmpty || false;   // 是否为透明背景
        this.minWidth = 1;
        this.maxWidth = 5;
        this.pointGroups = [];
        this.pointsDrawCurve = [];
        this._lastVelocity = 0;
        this.velocityFilterWeight = 0.7;
        this.touchAction = 'start';
        this._isEmpty = true;
        this._mouseButtonDown = false;
        this.useEraser = false;
        this.beginErase = false;
        this.firstPoint = {};
        this.clear();
        this.on();
    }

    get dotSize () {
        return (this.minWidth + this.maxWidth) / 2;
    }

    toDataURL (type = 'image/png', encoderOptions) {
        switch (type) {
            case 'image/svg+xml':
                return this._toSVG();
            default:
                return this.canvas.toDataURL(type, encoderOptions);
        }
    }

    on () {
        // Disable panning/zooming when touching canvas element
        this.canvas.style.touchAction = 'none';
        this.canvas.style.msTouchAction = 'none';

        this._handleTouchEvents();

        const throttle = (fn, delay = 50) => {
            let stattime = 0;
            return function(...args) {
              let curTime = new Date();
              if (curTime - stattime >= delay) {
                fn.apply(this, args);
                stattime = curTime;
              }
            };
        };

        this._strokeUpdateThrottle = throttle(this._strokeUpdate, 10);
    }

    _handleTouchEvents () {
        this.canvas.addEventListener('touchstart', event => {
            this.touchAction = 'start';
            this._handleTouchStart(event);
        });
        this.canvas.addEventListener('touchmove', event => {
            this._handleTouchMove(event);
        });
        this.canvas.addEventListener('touchend', event => {
            this.touchAction = 'end';
            this._handleTouchEnd(event);
        });
        this.canvas.addEventListener('mousedown', event => {
            this.touchAction = 'start';
            this._handleMouseDown(event);
        });
        this.canvas.addEventListener('mousemove', event => {
            this._handleMouseMove(event);
        });
        this.canvas.addEventListener('mouseup', event => {
            this.touchAction = 'end';
            this._handleMouseUp(event);
        });
    }

    setColor (color) {
        this.penColor = color;
    }

    clear () {
        const ctx = this._ctx;
        const canvas = this.canvas;

        // Clear canvas using background color
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // 设置画板背景色
        if (!this.backgroundIsEmpty) {
            ctx.fillStyle = this.backgroundColor;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        }

        this._data = [];
        this._reset();
        this._isEmpty = true;
    }

    _reset () {
        this.pointsDrawCurve = [];
        this._lastVelocity = 0;
        this._lastWidth = this.dotSize;
    }

    _handleTouchStart (event) {
        // Prevent scrolling.
        event.preventDefault();
        this._isEmpty = false;
        this.beginErase = this.useEraser;
        if (event.targetTouches.length === 1) {
            const touch = event.changedTouches[0];
            this._strokeBegin(touch);
        }
    }

    _handleTouchMove (event) {
        // Prevent scrolling.
        event.preventDefault();

        const touch = event.targetTouches[0];
        this._strokeUpdateThrottle(touch);
    }

    _handleTouchEnd (event) {
        if (this.penColor == '#fff') {
            this._handleEraser();
            return;
        }
        const wasCanvasTouched = event.target === this.canvas;
        if (wasCanvasTouched) {
            event.preventDefault();
            const touch = event.changedTouches[0];
            this._strokeEnd(touch);
        }
    }

    _handleMouseDown (event) {
        if (event.which === 1) {
            this._isEmpty = false;
            this._mouseButtonDown = true;
            this._strokeBegin(event);
        }
    }

    _handleMouseMove (event) {
        if (this._mouseButtonDown) {
            this._strokeUpdateThrottle(event);
        }
    }

    _handleMouseUp (event) {
        if (event.which === 1 && this._mouseButtonDown) {
            this._mouseButtonDown = false;
            this._strokeEnd(event);
        }
        if (this.penColor == '#fff') {
            this._handleEraser();
        }
    }

    _handleEraser (event) {
        let blank = document.createElement('canvas');
        let ctx = blank.getContext('2d');
        blank.width = this.canvas.width;
        blank.height = this.canvas.height;
        ctx.fillStyle = this.backgroundColor;
        ctx.clearRect(0, 0, blank.width, blank.height);
        ctx.fillRect(0, 0, blank.width, blank.height);
        if (blank.toDataURL('image/jpg') == this.canvas.toDataURL('image/jpg')) {
            this._isEmpty = true;
        }
        blank = null;
    }

    _strokeBegin (event) {
        const newPointGroup = {
            points: [],
        };

        this.pointGroups.push(newPointGroup);
        this._reset();
        this._strokeUpdate(event);
    }

    _strokeUpdate (event) {
        const x = event.clientX;
        const y = event.clientY;
        const point = this._createPoint(x, y);
        const curPointGroup = this.pointGroups[this.pointGroups.length - 1];
        const curPoints = curPointGroup.points;
        const lastPoint = curPoints.length > 0 && curPoints[curPoints.length - 1];
        const isLastPointTooClose = lastPoint ? point.distanceTo(lastPoint) <= this.minDistance : false;
        const color = this.penColor;
        // Skip this point if it's too close to the previous one
        if (!lastPoint || !(lastPoint && isLastPointTooClose && this.touchAction !== 'end')) {
            const curve = this.getCurve(point);
            if (!lastPoint) {
                this._drawDot({ color, point });
            } else if (curve) {
                this._drawCurve({ color, curve });
            }
            curPoints.push({
                time: point.time,
                x: point.x,
                y: point.y,
            });
        }
    }

    _strokeEnd (event) {
        this._strokeUpdate(event);
    }

    _createPoint (x, y) {
        const rect = this.canvas.getBoundingClientRect();
        return new Point(x - rect.left, y - rect.top, new Date().getTime());
    }

    // Add point to pointsDrawCurve array and generate a new curve if there are enough points (i.e. 3)
    getCurve (point) {
        const { pointsDrawCurve } = this;

        pointsDrawCurve.push(point);

        if (pointsDrawCurve.length > 2) {
            if (pointsDrawCurve.length === 3) {
                pointsDrawCurve.unshift(pointsDrawCurve[0]);
            }
            // pointsDrawCurve array will always have 3 points here.
            const widths = this._calculateCurveWidths(pointsDrawCurve[1], pointsDrawCurve[2]);
            const curve = Bezier.fromPoints(pointsDrawCurve, widths);
            // Remove the first element from the list, so that there are no more than 3 points at any time.
            pointsDrawCurve.shift();

            return curve;
        }

        return null;
    }

    _calculateCurveWidths (startPoint, endPoint) {
        const velocity =
            this.velocityFilterWeight * endPoint.velocityFrom(startPoint) +
            (1 - this.velocityFilterWeight) * this._lastVelocity;

        const newWidth = this._strokeWidth(velocity);

        const widths = {
            end: newWidth,
            start: this._lastWidth,
        };

        this._lastVelocity = velocity;
        this._lastWidth = newWidth;

        return widths;
    }

    _strokeWidth (velocity) {
        return Math.max(this.maxWidth / (velocity + 1), this.minWidth);
    }

    _drawCurve ({ color, curve }) {
        const ctx = this._ctx;
        ctx.beginPath();
        ctx.fillStyle = color;
        // '2' is just an arbitrary number here. If only lenght is used, then
        // there are gaps between curve segments :/
        const widthDelta = curve.endWidth - curve.startWidth;
        const drawSteps = Math.floor(curve.length() / 2);
        for (let i = 0; i < drawSteps; i += 1) {
            // Calculate the Bezier (x, y) coordinate for this step.
            const t = i / drawSteps;
            const tt = t * t;
            const ttt = tt * t;
            const u = 1 - t;
            const uu = u * u;
            const uuu = uu * u;
            let x = uuu * curve.startPoint.x;
            x += 3 * uu * t * curve.control1.x;
            x += 3 * u * tt * curve.control2.x;
            x += ttt * curve.endPoint.x;
            let y = uuu * curve.startPoint.y;
            y += 3 * uu * t * curve.control1.y;
            y += 3 * u * tt * curve.control2.y;
            y += ttt * curve.endPoint.y;
            let width;
            if (this.touchAction == 'end' && this.minWidth !== this.maxWidth) {
                width = Math.min(curve.startWidth - t * curve.startWidth);
            } else if (this.minWidth === this.maxWidth) {
                width = Math.min(curve.startWidth + ttt * widthDelta, this.maxWidth);
            } else {
                width = curve.startWidth + ttt * widthDelta;
            }
            this._drawCurveSegment(x, y, width);
        }
        ctx.fill();
        ctx.closePath();
    }

    _drawCurveSegment (x, y, width) {
        const ctx = this._ctx;
        ctx.moveTo(x, y);
        ctx.arc(x, y, width + 1, 0, 2 * Math.PI, false);
    }

    _drawDot ({ color, point }) {
        const ctx = this._ctx;
        const width = this.dotSize;
        ctx.beginPath();
        this._drawCurveSegment(point.x, point.y, width);
        ctx.closePath();
        ctx.fillStyle = color;
        ctx.fill();
    }
}
